package com.lbssoft.datalink;

import com.lbssoft.datalink.model.AuthMsg;
import com.lbssoft.datalink.model.Property;
import com.lbssoft.datalink.util.Constant;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.HashedWheelTimer;

import java.util.concurrent.TimeUnit;

import com.lbssoft.datalink.model.Constants;
import com.lbssoft.datalink.model.LoginMsg;
import com.lbssoft.datalink.util.Log;

public class SubServer {

    protected final HashedWheelTimer timer = new HashedWheelTimer();

    private Bootstrap boot;
    private SocketChannel socketChannel;
    private final ConnectorIdleStateTrigger idleStateTrigger = new ConnectorIdleStateTrigger();

    public SubServer() throws Exception {

    }

    public SubServer(Property logger) throws Exception {
        Log.setupLog(logger);
    }


    public void connect(String account, String password, String key, final SubServerHandler handler) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        boot = new Bootstrap();
        boot.group(group).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new LoggingHandler(LogLevel.INFO));

        final ConnectionWatchdog watchdog = new ConnectionWatchdog(boot, timer, Constant.PUB_SERVER_PORT, Constant.PUB_SERVER_HOST, account, password, key, true) {

            public ChannelHandler[] handlers() {
                return new ChannelHandler[]{
                        this,
                        new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS),
                        idleStateTrigger,
                        new ObjectEncoder(),
                        new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                        handler
                };
            }
        };

        ChannelFuture future;
        //进行连接
        try {
            synchronized (boot) {
                boot.handler(new ChannelInitializer<Channel>() {

                    //初始化channel
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(watchdog.handlers());
                    }
                });

                future = boot.connect(Constant.PUB_SERVER_HOST, Constant.PUB_SERVER_PORT).sync();
                if (future.isSuccess()) {
                    socketChannel = (SocketChannel) future.channel();
                    Log.info("Starting DataLink...");
                    Constants.setClientId(key);
                    LoginMsg loginMsg = new LoginMsg();
                    loginMsg.setAccount(account);
                    loginMsg.setPassword(password);
                    socketChannel.writeAndFlush(loginMsg);
                }
            }


        } catch (Throwable t) {
            throw new Exception("Starting DataLink fail...", t);
        }
    }

    public void connect(String appSecret, final SubServerHandler handler) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        boot = new Bootstrap();
        boot.group(group).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new LoggingHandler(LogLevel.INFO));

        final ConnectionWatchdog2 watchdog = new ConnectionWatchdog2(boot, timer, Constant.PUB_SERVER_PORT, Constant.PUB_SERVER_HOST, appSecret, true) {

            public ChannelHandler[] handlers() {
                return new ChannelHandler[]{
                        this,
                        new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS),
                        idleStateTrigger,
                        new ObjectEncoder(),
                        new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                        handler
                };
            }
        };

        ChannelFuture future;
        //进行连接
        try {
            synchronized (boot) {
                boot.handler(new ChannelInitializer<Channel>() {

                    //初始化channel
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(watchdog.handlers());
                    }
                });

                future = boot.connect(Constant.PUB_SERVER_HOST, Constant.PUB_SERVER_PORT).sync();
                if (future.isSuccess()) {
                    socketChannel = (SocketChannel) future.channel();
                    Log.info("Starting DataLink...");
                    Constants.setClientId(appSecret);
                    AuthMsg auth = new AuthMsg();
                    auth.setAppsecret(appSecret);
                    socketChannel.writeAndFlush(auth);
                }
            }


        } catch (Throwable t) {
            throw new Exception("Starting DataLink fail...", t);
        }
    }

}  